package net.minhdiep.androiddialoglistener;

import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import net.minhdiep.androiddialoglistener.components.SubBroadcastReceiver;
import net.minhdiep.androiddialoglistener.util.DownloadXmlBR;
import net.minhdiep.androiddialoglistener.util.XmlParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.util.Iterator;


/*
 * User: Minh Diep
 * Date: 5/18/13
 * Time: 11:55 PM
 */

public class BroadcastReceiverActivity extends Activity implements SubBroadcastReceiver.onListener{

    private TextView downloadXmlTv;
    private SubBroadcastReceiver subBroadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private IntentFilter intentFilter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_breceiver);

        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        subBroadcastReceiver = new SubBroadcastReceiver(this);
        intentFilter = new IntentFilter(SubBroadcastReceiver.INTENT_FILTER_NAME);
        intentFilter.addAction(SubBroadcastReceiver.DATA_RECEIVE_ACTION);

        Button downloadXmlBtn = (Button) findViewById(R.id.download_xml_btn);
        downloadXmlTv = (TextView) findViewById(R.id.download_xml_tv);
        downloadXmlBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                downloadXmlTv.setText("Loading...");
                new DownloadXmlBR(localBroadcastManager).execute("http://news.google.com/?output=rss");

            }

        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        localBroadcastManager.registerReceiver(subBroadcastReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        localBroadcastManager.unregisterReceiver(subBroadcastReceiver);
    }

    @Override
    public void onFinishDownloadXml(String s) {

        XmlParser xmlParser = new XmlParser();
        Document document = null;
        try {
            document = xmlParser.parse(s);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        assert document != null;
        Element channel = document.getRootElement().element("channel");
        String fun = "";
        for ( Iterator i = channel.elementIterator("item"); i.hasNext(); ) {
            Element item = (Element) i.next();
            fun += item.element("title").getText() + "\n\n";
        }
        downloadXmlTv.setText(fun);
    }
}